/*
 * Copyright 2011 Jonathan Komorek
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.jkomorek.eurl.selenium;

import org.jkomorek.eurl.selenium.exceptions.ScriptAssertionFailedException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.List;

public class ScriptRunner {

    private WebDriver webDriver;


    public void runScript(Script script) {
        beforeScript(script);
        try {
            System.out.println("Executing steps in script["+script.getTitle()+"]");
            List<Step> steps = script.getSteps();
            for (Step step: steps) {
                step.execute(this);
            }
        } catch (ScriptAssertionFailedException e) {
            System.err.println("Script failed during execution");
            e.printStackTrace(System.err);
        } finally {
            afterScript(script);
        }

    }

    /**
     * Called before running a script in order to setup anything we may need for execution.
     * @param script - the script we are about to execute
     *
     */
    public void beforeScript(Script script) {
        setWebDriver(new FirefoxDriver()); //TODO: Don't default to FireFox
    }


    /**
     * Called after running a script (even if it fails to complete) in order to clean up anything we may have created during execution.
     * @param script - the script we just completed execution of
     */
    public void afterScript(Script script) {
        getWebDriver().close();
    }

    public WebDriver getWebDriver() {
        return webDriver;
    }

    public void setWebDriver(WebDriver webDriver) {
        this.webDriver = webDriver;
    }

}
